<template>
  <div class="document-list">
    <!-- 头部工具栏 -->
    <el-card shadow="never" class="toolbar-card">
      <template #header>
        <div class="card-header">
          <span>文档管理</span>
        </div>
      </template>
      <el-space wrap :size="15">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文档..."
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="filterType"
          placeholder="文档类型"
          clearable
          style="width: 150px"
          @change="handleFilter"
        >
          <el-option label="全部" value="" />
          <el-option label="工单" value="workorder" />
          <el-option label="故障分析" value="fault_analysis" />
          <el-option label="设备说明书" value="equipment_manual" />
          <el-option label="其他" value="other" />
        </el-select>

        <el-divider direction="vertical" />

        <el-button @click="exportData" :icon="Download" :loading="exporting">导出</el-button>
        <el-button
          type="danger"
          @click="deleteSelected"
          :icon="Delete"
          v-if="selectedDocs.length > 0"
        >
          删除选中 ({{ selectedDocs.length }})
        </el-button>
        <el-button type="primary" @click="refreshList" :icon="Refresh" :loading="loading">刷新</el-button>
      </el-space>
    </el-card>

    <!-- 统计行 -->
    <el-card shadow="never" class="stats-card">
      <el-space>
        <el-text>共 <el-text type="primary" tag="strong">{{ kbStore.documents.length }}</el-text> 个文档</el-text>
        <el-divider direction="vertical" />
        <el-text v-if="selectedDocs.length > 0" type="primary">
          已选择 <el-text tag="strong">{{ selectedDocs.length }}</el-text> 个
        </el-text>
      </el-space>
    </el-card>

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        :data="filteredDocuments"
        v-loading="loading"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="source" label="来源" width="150" />
        <el-table-column prop="doc_type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.doc_type)">{{ getTypeLabel(row.doc_type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容预览" min-width="300" show-overflow-tooltip>
          <template #default="{ row }">
            <el-text truncated>{{ row.content.substring(0, 100) }}...</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" sortable>
          <template #default="{ row }">
            <el-text>{{ formatDate(row.created_at) }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button link type="primary" size="small" @click="viewDetail(row)">查看</el-button>
              <el-button link type="danger" size="small" @click="deleteDocument(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <template #footer>
        <div class="pagination-footer">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="filteredDocuments.length"
            layout="total, sizes, prev, pager, next, jumper"
            @pagination-change="handlePaginationChange"
          />
        </div>
      </template>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="showDetail" :title="`文档详情 - ${currentDetail?.source}`" width="70%">
      <el-descriptions v-if="currentDetail" :column="1" border>
        <el-descriptions-item label="来源">
          <el-text>{{ currentDetail.source }}</el-text>
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          <el-tag :type="getTypeColor(currentDetail.doc_type)">
            {{ getTypeLabel(currentDetail.doc_type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          <el-text>{{ formatDate(currentDetail.created_at) }}</el-text>
        </el-descriptions-item>
        <el-descriptions-item label="内容">
          <el-scrollbar height="400px">
            <el-text style="white-space: pre-wrap; word-wrap: break-word;">{{ currentDetail.content }}</el-text>
          </el-scrollbar>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Download, Delete, Refresh } from '@element-plus/icons-vue'
import { useKnowledgeBaseStore } from '@/stores/knowledge-base'

const route = useRoute()
const kbStore = useKnowledgeBaseStore()

const loading = ref(false)
const exporting = ref(false)
const searchQuery = ref('')
const filterType = ref('')
const selectedDocs = ref([])
const showDetail = ref(false)
const currentDetail = ref(null)
const currentPage = ref(1)
const pageSize = ref(20)

// 监听路由查询参数，自动设置搜索和过滤条件
watch(() => route.query, (query) => {
  if (query.source) {
    searchQuery.value = query.source
  }
  if (query.docType) {
    filterType.value = query.docType
  }
}, { immediate: true })

const typeMap = {
  workorder: '工单',
  fault_analysis: '故障分析',
  equipment_manual: '设备说明书',
  other: '其他'
}

const typeColorMap = {
  workorder: 'info',
  fault_analysis: 'warning',
  equipment_manual: 'success',
  other: 'default'
}

const filteredDocuments = computed(() => {
  let docs = kbStore.documents

  // 按类型过滤
  if (filterType.value) {
    docs = docs.filter(d => d.doc_type === filterType.value)
  }

  // 按搜索关键词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    docs = docs.filter(d =>
      d.source?.toLowerCase().includes(query) ||
      d.content?.toLowerCase().includes(query)
    )
  }

  return docs
})

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleSelectionChange = (selection) => {
  selectedDocs.value = selection.map(d => d.id)
}

const getTypeLabel = (type) => {
  return typeMap[type] || type
}

const getTypeColor = (type) => {
  return typeColorMap[type] || 'default'
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

const refreshList = async () => {
  loading.value = true
  try {
    await kbStore.fetchDocuments()
    ElMessage.success('文档列表已更新')
  } catch (err) {
    ElMessage.error('更新失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

const viewDetail = (doc) => {
  currentDetail.value = doc
  showDetail.value = true
}

const deleteDocument = async (docId) => {
  ElMessageBox.confirm(
    '确定要删除这个文档吗？删除后将无法恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const result = await kbStore.deleteDocument(docId)
      // 检查返回结果
      if (result && result.success) {
        ElMessage.success(`${result.message || '文档已删除'}`)
      } else if (result && result.error) {
        ElMessage.error('删除失败: ' + result.error)
        return
      }
      // 删除成功，刷新列表
      await refreshList()
    } catch (err) {
      ElMessage.error('删除失败: ' + (err.message || err.detail || '未知错误'))
    }
  }).catch(() => {
    // 用户取消
  })
}

const deleteSelected = async () => {
  if (selectedDocs.value.length === 0) return

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedDocs.value.length} 个文档吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const result = await kbStore.deleteDocumentsBatch(selectedDocs.value)
      // 检查返回结果
      if (result && result.success) {
        ElMessage.success(`${result.message || '文档已批量删除'}`)
      } else if (result && result.error) {
        ElMessage.error('批量删除失败: ' + result.error)
        return
      }
      // 删除成功，清空选中和刷新列表
      selectedDocs.value = []
      await refreshList()
    } catch (err) {
      ElMessage.error('批量删除失败: ' + (err.message || err.detail || '未知错误'))
    }
  }).catch(() => {
    // 用户取消
  })
}

const exportData = async () => {
  exporting.value = true
  try {
    await kbStore.exportKB()
    ElMessage.success('知识库已导出')
  } catch (err) {
    ElMessage.error('导出失败: ' + err.message)
  } finally {
    exporting.value = false
  }
}

const handlePaginationChange = () => {
  // 分页变化时的处理
}

onMounted(async () => {
  loading.value = true
  try {
    await kbStore.fetchDocuments()
  } catch (err) {
    ElMessage.error('加载文档列表失败: ' + err.message)
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.document-list {
  padding: 0;
}

.toolbar-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
}

.stats-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-footer {
  display: flex;
  justify-content: center;
  padding-top: 15px;
}

.action-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

@media (max-width: 768px) {
  :deep(.el-table) {
    font-size: 12px;
  }
}
</style>

